package com.acceptable.qucun.generic.util;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.lang.NonNull;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class FileUtil {
    public static String changeFileNameByDate(@NonNull String fileName,
                                              @NonNull Date date){
        fileName = StringFormatUtil.clearDate(fileName);
        String time = TimeUtil.date2LocalDateTime(date)
                .toString()
                .replace(":", "-")
                .replace(" ", "_")
                .replace("T", "_");
        fileName = time + "_" + fileName;
        return fileName;
    }

    private static String getMime(@NonNull InputStream in)
            throws TikaException, SAXException, IOException {
        ContentHandler contenthandler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        AutoDetectParser parser = new AutoDetectParser();
        parser.parse(in, contenthandler, metadata);
        System.out.println(metadata.get(Metadata.CONTENT_TYPE));
        return metadata.get(Metadata.CONTENT_TYPE);
    }

    public static String getMimeByFilePath(@NonNull String filePath)
            throws TikaException, SAXException, IOException {
        InputStream in = new FileInputStream(filePath);
        return getMime(in);
    }

    public static String getMimeByFile(@NonNull File file)
            throws TikaException, SAXException, IOException {
        InputStream in = new FileInputStream(file);
        return getMime(in);
    }

//    public static void filePhysicalDeleteTask(@NonNull TemplateFileMapper){
//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//            }
//        };
//        //创建timer对象设置间隔时间
//        Timer timer = new Timer();
//        // 间隔天数
//        long delay = 0;
//        // 间隔毫秒数
//        long period = 1000;
//        timer.scheduleAtFixedRate(timerTask, delay, period);
//    }
}

